const { getConnection } = require('./index');

async function withTransaction(fn) {
  const conn = await getConnection();

  try {
    await conn.beginTransaction();
    const result = await fn(conn);
    await conn.commit();
    return result;

  } catch (error) {
    await conn.rollback();
    throw error;
  } finally {
    conn.release();
  }

}

module.exports = {
  withTransaction
}
